//
//  FirstViewController.m
//  Login
//
//  Created by FER on 22/10/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "FirstViewController.h"
#import "LoginAppDelegate.h"
#import "ConnectionHTTP.h"
#import "NewsDetails.h"

@implementation FirstViewController

@synthesize newsDetailsView;

NewsDetails *newViewNews;
NSMutableArray *listOfNews;
NSMutableArray *listOfNews_ID;

//NSMutableArray *dataArray = [[NSMutableArray alloc] initWithCapacity: 3];
//[dataArray insertObject:[NSMutableArray arrayWithObjects:@"0",@"0",@"0",nil] atIndex:0];

//---insert individual row into the table view---
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *CellIdentifier = @"Cell";
	
	//---try to get a reusable cell---
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	
	//---create new cell if no reusable cell is available---
	if (cell == nil) { 
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
												  reuseIdentifier:CellIdentifier] 
													autorelease];
	}
	
	//---set the text to display for the cell---
	NSString *cellValue = [listOfNews objectAtIndex:indexPath.row]; 
	cell.textLabel.text = cellValue;
	
	return cell;

}

//---set the number of rows in the table view---
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [listOfNews count];
}

-(void)viewDidLoad
{ 
	self.navigationItem.title = @"List of Movies";
	
	listOfNews = [[NSMutableArray alloc] init];
	listOfNews_ID = [[NSMutableArray alloc] init];
	NSString *newsURL = [NSString stringWithFormat:@"ios/news.php"];
	NSString *newsResponse= [ConnectionHTTP doRequest:(NSString *)newsURL];
	
	//Parse XML
	xmlBuffer = [ [ newsResponse stringByReplacingOccurrencesOfString: @"<" withString :@"\n<" ] 
				 componentsSeparatedByCharactersInSet: [ NSCharacterSet newlineCharacterSet ] ];
	
	for(int i = 0; i < [ xmlBuffer count ]; i++) 
	{
		NSString *line = [ xmlBuffer objectAtIndex: i ];
		if ([ line hasPrefix: @"<NEWS>" ]) 
		{
			NSString *id_news;
			NSString *title;
			NSString *date;
			
			while(!([ line isEqualToString: @"</NEWS>" ])) 
			{
				if ([ line hasPrefix: @"<ID>" ]) {
					id_news  = [ line stringByReplacingOccurrencesOfString: @"<ID>" withString: @"" ];		
				}
				if ([ line hasPrefix: @"<TITLE>" ]) 
				{
					title  = [ line stringByReplacingOccurrencesOfString: @"<TITLE>" withString: @"" ];		
				}
				if ([ line hasPrefix: @"<DATE>" ]) 
				{
					date  = [ line stringByReplacingOccurrencesOfString: @"<DATE>" withString: @"" ];		
				}
				i++;
				line = [ xmlBuffer objectAtIndex: i ];
			}
			NSString *line= [NSString stringWithFormat:@"%@  DATE: %@",title,date];
			[listOfNews addObject:line]; 
			[listOfNews_ID addObject:id_news];
			NSLog(@"%@ ID: %@",line,id_news);
			
		}
	}
	
		[super viewDidLoad];

}
	

-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
	NSLog(@"didSelectRowAtIndexPath");
	int indexSelected = indexPath.row;
	NSInteger selected = indexSelected;
	IDdelSeleccionado = [listOfNews_ID objectAtIndex:selected];

	
	//---add the view of the view controller to the current View---
	//---Navigate to the details view---
	if (self.newsDetailsView == nil) 
	{ 
		NSString *title;
		NSString *body;
		NSString *date;
		NSString *author;
		
		NSString *newsURL = [NSString stringWithFormat:@"ios/getNewsBody.php?newsID=%@",IDdelSeleccionado];
		//NSString *newsURL = [NSString stringWithFormat:@"http://inspiron15/ios/body.php"];
		NSString *newsResponse= [ConnectionHTTP doRequest:(NSString *)newsURL];
		NSLog(@"RESPONSE: %@",newsResponse);
		
		//Parse XML
		xmlBuffer = [ [ newsResponse stringByReplacingOccurrencesOfString: @"<" withString :@"\n<" ] componentsSeparatedByCharactersInSet: [ NSCharacterSet newlineCharacterSet ] ];
		
		for(int i = 0; i < [ xmlBuffer count ]; i++) 
		{
			NSString *line = [ xmlBuffer objectAtIndex: i ];
		
					if ([ line hasPrefix: @"<TITLE>" ]) {
						title  = [ line stringByReplacingOccurrencesOfString: @"<TITLE>" withString: @"" ];		
					}
					if ([ line hasPrefix: @"<BODY>" ]) {
						body  = [ line stringByReplacingOccurrencesOfString: @"<BODY>" withString: @"" ];		
					}
					if ([ line hasPrefix: @"<DATE>" ]) {
						date  = [ line stringByReplacingOccurrencesOfString: @"<DATE>" withString: @"" ];		
					}
					if ([ line hasPrefix: @"<AUTHOR>" ]) {
						author  = [ line stringByReplacingOccurrencesOfString: @"<AUTHOR>" withString: @"" ];		
					}
		}
		
		//Nueva pantalla.
		newViewNews = [[NewsDetails alloc] initWithNibName:@"NewsDetails" bundle:[NSBundle mainBundle]];
		[self.view addSubview:newViewNews.view];
		
		[newViewNews.labelTitle setText:title];
		[newViewNews.labelDate setText:date];
		//[newViewNews.labelBody setText:body];
		[newViewNews.TextBody setText:body];
		[newViewNews.labelAuthor setText:author];
	}
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
		//---display “Movie List” as the header---
		return @"Lista de noticias";
}
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
	//---display “by Denzel Washington” as the footer---
	return @"Mostrados los ultimos 10 elementos";
}



// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[newViewNews release];
	[listOfNews_ID release];
	[listOfNews release];
    [super dealloc];
}

@end
